<?php
namespace Jykj\Mass\Controller;

use TYPO3\CMS\Core\Utility\GeneralUtility;

/***************************************************************
 *
 *  Copyright notice
 *
 *  (c) 2017 WHB <wanghongbin@ngoos.org>, 极益科技
 *
 *  All rights reserved
 *
 *  This script is part of the TYPO3 project. The TYPO3 project is
 *  free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  The GNU General Public License can be found at
 *  http://www.gnu.org/copyleft/gpl.html.
 *
 *  This script is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  This copyright notice MUST APPEAR in all copies of the script!
 ***************************************************************/

/**
 * MailController
 */
class MailController extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController
{

    /**
     * mailRepository
     *
     * @var \Jykj\Mass\Domain\Repository\MailRepository
     * @inject
     */
    protected $mailRepository = NULL;
    
    /**
     * logRepository
     *
     * @var \Jykj\Mass\Domain\Repository\LogRepository
     * @inject
     */
    protected $logRepository = NULL;
    
    protected $filePath = '';
    
    protected $basePath = '';
    
    protected $senderEmail = '';
    
    protected $senderName = '';
    
    public function initializeAction()
    {
        if (!is_dir(PATH_site . 'uploads/tx_mass_attach/')) {
            mkdir(PATH_site . 'uploads/tx_mass_attach/', 511);
        }
        $this->filePath = PATH_site . 'uploads/tx_mass_attach/';
        $this->basePath = GeneralUtility::getIndpEnv('TYPO3_SITE_URL') . 'uploads/tx_mass_attach/';
        $this->senderEmail = $GLOBALS['TYPO3_CONF_VARS']['MAIL']['defaultMailFromAddress'];
        $this->senderName = $GLOBALS['TYPO3_CONF_VARS']['MAIL']['defaultMailFromName'];
    }
    
    /**
     * action list
     *
     * @return void
     */
    public function listAction()
    {
        $svalid = $this->request->hasArgument('svalid') ? $this->request->getArgument('svalid') : '';
        $evalid = $this->request->hasArgument('evalid') ? $this->request->getArgument('evalid') : '';
        $keyword = $this->request->hasArgument('keyword') ? $this->request->getArgument('keyword') : '';
        $mails = $this->mailRepository->findAlls($svalid, $evalid, $keyword);
        if ($_GET['tx_mass_mail']['@widget_0']['currentPage']) {
            $page = $_GET['tx_mass_mail']['@widget_0']['currentPage'];
        } else {
            $page = 1;
        }
        $this->view->assign('page', $page);
        $this->view->assign('mails', $mails);
        $this->view->assign('svalid', $svalid);
        $this->view->assign('evalid', $evalid);
        $this->view->assign('keyword', $keyword);
        $this->view->assign('form',GeneralUtility::getIndpEnv('TYPO3_REQUEST_URL'));

        //excel export
        if($this->request->hasArgument('excelExport')){
            $phpExcelService = GeneralUtility::makeInstanceService('phpexcel');
            $phpExcel = $phpExcelService->getPHPExcel();
            $sheet  = $phpExcel->setActiveSheetIndex(0);
            $dataArray[] = array('序号', '邮件主题', '邮件内容', '发送时间', '模板调用名称', '发送状态', '成功率', '总计');
            if(count($mails)){
                $i = 1;
                foreach($mails as $mail){
                    $dataArray[] = array(
                        $i++,
                        $mail->getTitle(),
                        $mail->getBodytext(),
                        date('Y-m-d H:i', $mail->getCrdate()),
                        $mail->getAttach(),
                        $mail->getSendStstus()==0?'未发送':'已发送',
                        $mail->getSuccessRate().'%',
                        $mail->getTotal().'条'
                    );
                }
                $sheet->fromArray($dataArray, NULL, 'A1');
                $objWriter = $phpExcelService->getInstanceOf('PHPExcel_Writer_Excel2007', $phpExcel);
                $fileName = '群发邮件列表_'.date('Y-m-d');
                header('Pragma: public');
                header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
                header('Content-Type: application/force-download');
                header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
                header('Content-Disposition: attachment;filename="'.$fileName.'.xlsx"');
                header('Cache-Control: max-age=0');
                $objWriter->save('php://output');
                exit;
            }
        }
    }
    
    /**
     * action show
     *
     * @param \Jykj\Mass\Domain\Model\Mail $mail
     * @return void
     */
    public function showAction(\Jykj\Mass\Domain\Model\Mail $mail)
    {
        preg_match("/\<body\>(.*?)\<\/body\>/is", $mail->getBodytext(), $matches);
        if(isset($matches[1])){
            $mail->setBodytext($matches[1]);
        }
        $this->view->assign('mail', $mail);
    }
    
    /**
     * action new
     *
     * @return void
     */
    public function newAction()
    {
        //excel import
        if ($this->request->hasArgument('receiver')) {
            $file = $this->request->getArgument('receiver');
            $fI = GeneralUtility::split_fileref($file['name']);
            if (GeneralUtility::inList('xls,xlsx', $fI['fileext'])) {
                $objPHPReader = $this->objectManager->get($fI['fileext'] == 'xls' ? 'PHPExcel_Reader_Excel5' : 'PHPExcel_Reader_Excel2007');
                $objPHPExcel = $objPHPReader->load($file['tmp_name']);
                $currentSheet = $objPHPExcel->getSheet(0);
                $allRow = $currentSheet->getHighestRow();
                $i = 0;
                $mailStr = '';
                for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                    if ($currentSheet->getCell('B' . $currentRow)->getValue() != '') {
                        $name = $currentSheet->getCell('A' . $currentRow)->getValue();
                        $email = $currentSheet->getCell('B' . $currentRow)->getValue();
                        $mailStr .= $name . '<' . $email . '>,';
                        $i++;
                    }
                }
                $mailStr = rtrim($mailStr, ',');
                $mail = new \Jykj\Mass\Domain\Model\Mail();
                $mail->setReceiver($mailStr);
                $this->view->assign('mail', $mail);
                $this->addFlashMessage('已成功上传“' . $i . '”条数据', '', \TYPO3\CMS\Core\Messaging\AbstractMessage::OK);
            } else {
                $this->addFlashMessage('文件格式不正确，请上传xls, xlsx格式文件。', '', \TYPO3\CMS\Core\Messaging\AbstractMessage::OK);
            }
        }
        $sendname = $GLOBALS['TSFE']->fe_user->user['name'];
        $this->view->assign('sendname', $sendname);
        if ($this->settings['api_user']!='' && $this->settings['api_key']!='') {
            $this->view->assign('emailTemplateArray', $this->getEmailTemplate($this->settings['api_user'],$this->settings['api_key']));
        }
    }
    
    /**
     * action create
     *
     * @param \Jykj\Mass\Domain\Model\Mail $mail
     * @return void
     */
    public function createAction(\Jykj\Mass\Domain\Model\Mail $mail)
    {
        // 指数函数<lele454194741@qq.com>
        $mail->setSender($this->senderName . '<' . $this->senderEmail . '>');
        $receiverStr = $mail->getReceiver();
        $receiverArr = $this->getNameAndEmail($receiverStr);
        $attach = end(explode('/', $mail->getAttach()));
        $mail->setTotal(count($receiverArr));
        $result = $this->getEmailTemplateMessage($this->settings['api_user'],$this->settings['api_key'],$mail->getAttach());
        if ($result['statusCode'] == 200) {
            $mail->setTitle($result['info']['data']['subject']);
            $mail->setBodytext($result['info']['data']['html']);
            if ($mail->getSendStstus() == 0) {
                $this->addFlashMessage('邮件已保存为草稿！', '', \TYPO3\CMS\Core\Messaging\AbstractMessage::OK);
                $this->mailRepository->add($mail);
            } else {
                $countUp = count(explode(',', $receiverStr));
                $countOn = count($receiverArr);
                $percent = sprintf('%.2f', $countOn / $countUp) * 100;
                $mail->setSendStstus(1);
                $mail->setSuccessRate($percent);
                $this->addFlashMessage('邮件已发送！', '', \TYPO3\CMS\Core\Messaging\AbstractMessage::OK);
                $this->mailRepository->add($mail);
                $persistenceManager = $this->objectManager->get(\TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager::class);
                $persistenceManager->persistAll();
                $suatu = $this->sendEMAIL($mail->getSender(),$mail->getTitle(),$mail->getBodytext(),$receiverArr, $mail->getAttach(),$mail->getUid());
            
            }
        }
        $this->redirect('list');
    }
    
    /**
     * action edit
     *
     * @ignorevalidation $mail
     * @param \Jykj\Mass\Domain\Model\Mail $mail
     * @return void
     */
    public function editAction(\Jykj\Mass\Domain\Model\Mail $mail)
    {
        $this->view->assign('mail', $mail);
        //excel import
        if ($this->request->hasArgument('receiver')) {
            $file = $this->request->getArgument('receiver');
            $fI = GeneralUtility::split_fileref($file['name']);
            if (GeneralUtility::inList('xls,xlsx', $fI['fileext'])) {
                $objPHPReader = $this->objectManager->get($fI['fileext'] == 'xls' ? 'PHPExcel_Reader_Excel5' : 'PHPExcel_Reader_Excel2007');
                $objPHPExcel = $objPHPReader->load($file['tmp_name']);
                $currentSheet = $objPHPExcel->getSheet(0);
                $allRow = $currentSheet->getHighestRow();
                $i = 0;
                $mailStr = '';
                for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                    if ($currentSheet->getCell('B' . $currentRow)->getValue() != '') {
                        $name = $currentSheet->getCell('A' . $currentRow)->getValue();
                        $email = $currentSheet->getCell('B' . $currentRow)->getValue();
                        $mailStr .= $name . '<' . $email . '>,';
                        $i++;
                    }
                }
                $mailStr = rtrim($mailStr, ',');
                $mail = new \Jykj\Mass\Domain\Model\Mail();
                $mail->setReceiver($mailStr);
                $this->view->assign('mail', $mail);
                $this->addFlashMessage('已成功上传“' . $i . '”条数据', '', \TYPO3\CMS\Core\Messaging\AbstractMessage::OK);
            } else {
                $this->addFlashMessage('文件格式不正确，请上传xls, xlsx格式文件。', '', \TYPO3\CMS\Core\Messaging\AbstractMessage::OK);
            }
        }
        $sendname = $GLOBALS['TSFE']->fe_user->user['name'];
        $this->view->assign('sendname', $sendname);
        if ($this->settings['api_user']!='' && $this->settings['api_key']!='') {
            $this->view->assign('emailTemplateArray', $this->getEmailTemplate($this->settings['api_user'],$this->settings['api_key']));
        }
    }
    
    /**
     * action update
     *
     * @param \Jykj\Mass\Domain\Model\Mail $mail
     * @return void
     */
    public function updateAction(\Jykj\Mass\Domain\Model\Mail $mail)
    {
        $mail->setSender($this->senderName . '<' . $this->senderEmail . '>');
        $receiverStr = $mail->getReceiver();
        $receiverArr = $this->getNameAndEmail($receiverStr);
        $attach = end(explode('/', $mail->getAttach()));
        $mail->setTotal(count($receiverArr));
        $result = $this->getEmailTemplateMessage($this->settings['api_user'],$this->settings['api_key'],$mail->getAttach());
        if ($result['statusCode'] == 200) {
            $mail->setTitle($result['info']['data']['subject']);
            $mail->setBodytext($result['info']['data']['html']);
            if ($mail->getSendStstus() == 0) {
                $this->addFlashMessage('邮件已保存为草稿！', '', \TYPO3\CMS\Core\Messaging\AbstractMessage::OK);
                $this->mailRepository->update($mail);
            } else {
                $countUp = count(explode(',', $receiverStr));
                $countOn = count($receiverArr);
                $percent = sprintf('%.2f', $countOn / $countUp) * 100;
                $mail->setSendStstus(1);
                $mail->setSuccessRate($percent);
                $this->addFlashMessage('邮件已发送！', '', \TYPO3\CMS\Core\Messaging\AbstractMessage::OK);
                $this->mailRepository->update($mail);
                $persistenceManager = $this->objectManager->get(\TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager::class);
                $persistenceManager->persistAll();
                $suatu = $this->sendEMAIL($mail->getSender(),$mail->getTitle(),$mail->getBodytext(),$receiverArr,$mail->getAttach(),$mail->getUid());
            
            }
        }
        $this->redirect('list');
    }
    
    /**
     * [subInfoAction description]
     *
     * @param \Jykj\Mass\Domain\Model\Mail $mail
     * @return [type] [description]
     */
    public function subInfoAction(\Jykj\Mass\Domain\Model\Mail $mail)
    {
        $receiverStr = $mail->getReceiver();
        $receiverArr = $this->getNameAndEmail($receiverStr);
        $countUp = count(explode(',', $receiverStr));
        $countOn = count($receiverArr);
        $percent = sprintf('%.2f', $countOn / $countUp) * 100;
        $attach = end(explode('/', $mail->getAttach()));
        $mail->setTotal(count($receiverArr));
        $result = $this->getEmailTemplateMessage($this->settings['api_user'],$this->settings['api_key'],$mail->getAttach());
        if ($result['statusCode'] == 200) {
            $mail->setTitle($result['info']['data']['subject']);
            $mail->setBodytext($result['info']['data']['html']);
            $mail->setSendStstus(1);
            $mail->setSuccessRate($percent);
            $this->addFlashMessage('邮件已发送！', '', \TYPO3\CMS\Core\Messaging\AbstractMessage::OK);
            $this->mailRepository->update($mail);
            $persistenceManager = $this->objectManager->get(\TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager::class);
            $persistenceManager->persistAll();
            $suatu = $this->sendEMAIL($mail->getSender(), $mail->getTitle(), $mail->getBodytext(), $receiverArr, $mail->getAttach(),$mail->getUid());
                    }
        $this->redirect('list');
    }
    
    /**
     * action tailLog
     *
     * @return void
     */
    public function tailLogAction()
    {
        $type = $this->request->hasArgument('type')?$this->request->getArgument('type'):'';
        if ($type=='0') {
            $massuid = $this->request->hasArgument('massuid')?$this->request->getArgument('massuid'):'';
            $keyword = $this->request->hasArgument('keyword')?$this->request->getArgument('keyword'):'';
            $form = $this->request->hasArgument('form')?$this->request->getArgument('form'):'';
            $logs = $this->logRepository->findTheTypeAndUid('mail',$massuid,$keyword);
            if ($_GET['tx_mass_mail']['@widget_0']['currentPage']) {
                $page = $_GET['tx_mass_mail']['@widget_0']['currentPage'];
            } else {
                $page = 1;
            }
            $this->view->assign('massuid', $massuid);
            $this->view->assign('logs', $logs);
            $this->view->assign('page', $page);
            $this->view->assign('type', $type);
            $this->view->assign('form', $form);
        }
    }
    
    /**
     * action delete
     *
     * @param \Jykj\Mass\Domain\Model\Mail $mail
     * @return void
     */
    public function deleteAction(\Jykj\Mass\Domain\Model\Mail $mail)
    {
        $this->addFlashMessage('邮件已删除！', '', \TYPO3\CMS\Core\Messaging\AbstractMessage::OK);
        $this->mailRepository->remove($mail);
        $this->redirect('list');
    }
    
    /**
     * action multedelete
     *
     * @return void
     */
    public function multedeleteAction()
    {
        
    }
    
    /**
     * action success
     *
     * @return void
     */
    public function successAction()
    {
        
    }
    
    /**
     * 获取长字符串中的名字和邮箱
     *
     * @param [type] $longReceiverStr [description]
     * @return [type]                  [description]
     */
    public function getNameAndEmail($longReceiverStr)
    {
        $longreceiverArr = explode(',', $longReceiverStr);
        $receiverArr = array();
        foreach ($longreceiverArr as $key => $value) {
            $name = strstr($value, '<', true);
            $email = strstr($value, '<');
            $email = rtrim($email, '>');
            $email = ltrim($email, '<');
            if (GeneralUtility::validEmail($email)) {
                $receiverArr[] = array(
                    'name' => $name,
                    'email' => $email
                );
            }
        }
        return $receiverArr;
    }
    
    /**
     * 获取邮件模板
     * @param  [type] $apiUser [description]
     * @param  [type] $apiKey  [description]
     * @return [type]          [description]
     */
    public function getEmailTemplate($apiUser,$apiKey)
    {
        $emailTemplateArray = [];
        $url = 'http://api.sendcloud.net/apiv2/template/list';
        $param = array(
            'apiUser' => $apiUser, # 使用api_user和api_key进行验证
            'apiKey' => $apiKey
        );
        $data = http_build_query($param);
        $options = array(
            'http' => array(
                'method' => 'POST',
                'header' => 'Content-Type: application/x-www-form-urlencoded',
                'content' => $data
            ));
        $context = stream_context_create($options);

        $result = json_decode(file_get_contents($url, FILE_TEXT, $context), true);
        if ($result['statusCode'] == 200) {
            foreach ($result['info']['dataList'] as $item) {
                $emailTemplateArray[$item['invokeName']] = $item['name'].' ('.($item['templateType']?'批量':'触发').')';
            }
        }
        return $emailTemplateArray;
    }

    /**
     * 获取邮件模板信息
     * @param  [type] $apiUser [description]
     * @param  [type] $apiKey  [description]
     * @param  [type] $template  [description]
     * @return [type]          [description]
     */
    public function getEmailTemplateMessage($apiUser,$apiKey,$template)
    {
        $url = 'http://api.sendcloud.net/apiv2/template/get';
        $param = array(
            'apiUser' => $apiUser, # 使用api_user和api_key进行验证
            'apiKey' => $apiKey,
            'invokeName' => $template
        );
        $data = http_build_query($param);
        $options = array(
            'http' => array(
                'method' => 'POST',
                'header' => 'Content-Type: application/x-www-form-urlencoded',
                'content' => $data
            ));
        $context = stream_context_create($options);
        $result = json_decode(file_get_contents($url, FILE_TEXT, $context), true);
        
        return $result;
    }

    /**
     * @param $sender
     * @param $title
     * @param $body
     * @param $recipients
     * @param $invokename
     * @param $mailuid
     * @return string
     */
    function sendEMAIL($sender, $title, $body, $recipients, $invokename,$mailuid)
    {
        $API_USER = $this->settings['api_user'];
        $API_KEY = $this->settings['api_key'];
        //不同于登录SendCloud站点的帐号，您需要登录后台创建发信子帐号，使用子帐号和密码才可以进行邮件的发送。
        $toArray = [];
        $params = [];
        foreach ($recipients as $recipient) {
            $toArray[] = $recipient['email'];
            foreach ($recipient as $key => $val) {
                $params['%' . $key . '%'][] = $val;
            }
        }
        $url = 'http://api.sendcloud.net/apiv2/mail/sendtemplate';
        $vars = json_encode(array(
            "to" => $toArray,
            "sub" => $params
        ));
        $param = array(
            'apiUser' => $API_USER, # 使用api_user和api_key进行验证
            'apiKey' => $API_KEY,
            'from' => $this->senderEmail,
            'fromName' => $sender,
            'xsmtpapi' => $vars,
            'templateInvokeName' => $invokename,
            'subject' => $title,
            'respEmailId' => 'true'
        );
        $data = http_build_query($param);

        $options = array(
            'http' => array(
                'method' => 'POST',
                'header' => 'Content-Type: application/x-www-form-urlencoded',
                'content' => $data
            ));
        $context = stream_context_create($options);

        $result = json_decode(file_get_contents($url, FILE_TEXT, $context), true);

        if ($result['statusCode'] != 200) {
            return ['error' => $result['message']];
        }
        foreach ($recipients as $recipient) {
            $this->addLogs('mail',$sender,$mailuid,$recipient,1,$result['message']);
        }

        return 'success';
    }

    //返回当前的毫秒时间戳
    public function msectime()
    {
        list($msec, $sec) = explode(' ', microtime());
        $msectime = (double) sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        return $msectime;
    }
    
    /**
     * 添加发送记录
     * @param [type] $type     [description]
     * @param [type] $sender   [description]
     * @param [type] $smsUid   [description]
     * @param [type] $receiver [description]
     * @param [type] $status   [description]
     * @param [type] $message  [description]
     */
    public function addLogs($type,$sender,$smsUid,$receiver,$status,$message)
    {
        $smsLog = new \Jykj\Mass\Domain\Model\Log();
        $smsLog->setType($type);
        $smsLog->setSender($sender);
        $smsLog->setMailuid($smsUid);
        $smsLog->setReceiver($receiver['name'].'<'.$receiver['email'].'>');
        $smsLog->setSuatus($status);
        $smsLog->setMessage($message);
        $this->logRepository->add($smsLog);
    }
}